"""
--------------------------------------
FileName: test.py
Content: 
    数据结构第二周第一次作业:
        检测对 @ 语句频度估算的正确性。

Date:    25/09/15
Auther:  杨则瑞
Encode:  utf-8 | CRLF
--------------------------------------
"""



import csv
import subprocess
import io
import os

from math import sqrt
from math import floor

testCases = []
testCases.extend(list(range(1,100)))
testCases.extend([1024,245,352,147,836,47])

# 表示正确结果的表达式
estimations = {
    1:"n-1",
    2:"max(n-1,1)",
    3:"n-1",
    4:"n*(n+1)/2",
    5:"n*(n+1)*(n+2)/6",
    6:"n",
    7:"floor(sqrt(n))",
    8:"1100"
}


failCnt = 0
for case in testCases:
    print("Testing case: \"n = {}\"".format(case).ljust(25),
          end="")
    
    target = os.path.join(os.path.dirname(__file__), ("main.terminal.exe"))

    handler = subprocess.Popen(target,
                           stdin  = subprocess.PIPE,
                           stdout = subprocess.PIPE,
                           stderr = subprocess.STDOUT)

    
    flag : bool = True

    if not handler.stdin.writable:

        print("Communication Error.")
        exit(1)
    
    if not handler.stdout.readable:
    
        print("Communication Error.")
        exit(2)


    n = str(case)
    answerTable , _ = handler.communicate(bytes(n,"utf-8"))
    answerTable = answerTable.decode()
    answerTable = csv.reader(io.StringIO(answerTable))

    n = int(n)
    for entry in answerTable:

        if answerTable.line_num <= 1:
            continue

        e_val = eval(estimations[int(entry[0])])
        r_val = int(entry[1])

        if r_val != e_val:
            failcode = "at {}. Expected {} read {}".format(int(entry[0]),r_val,e_val)
            flag = False
            break
    
    if(flag == True):
        print("\033[1;32m""Pass""\033[0;10m")
    else:
        failCnt += 1
        print("\033[1;31m"+"Fail: {}".format(failcode)+"\033[0;10m") 
                
print("Result:")

if failCnt == 0:
    print("\033[1;32m""All Pass.""\033[0;10m")
else :
    print("\033[1;10m""{} Fails cases".format(failCnt))